﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Business.EntityFrameworkCore;
using mozhi.smarterp.Business.Sales;
using mozhi.smarterp.Business.Sales.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories.Sale
{
    public class SaleProductPriceRepository : EfCoreRepository<BusinessDbContext, SaleProductPrice, Guid>, ISaleProductPriceRepository
    {
        public SaleProductPriceRepository(IDbContextProvider<BusinessDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<long> GetCountAsync(string keyword, string code, string name, Guid? customerId, Guid? currencyId, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<SaleProductPrice>().AsNoTracking()
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.Code.Contains(keyword) || x.Name.Contains(keyword))
                .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
                .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
                .WhereIf(customerId.HasValue, x => x.CustomerId == customerId)
                .WhereIf(currencyId.HasValue, x => x.CurrencyId == currencyId)
                .CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<SaleProductPrice>> GetPagedListAsync(string keyword, string code, string name, Guid? customerId, Guid? currencyId, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var entities = await dbContext.Set<SaleProductPrice>().AsNoTracking()
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.Code.Contains(keyword) || x.Name.Contains(keyword))
                .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
                .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
                .WhereIf(customerId.HasValue, x => x.CustomerId == customerId)
                .WhereIf(currencyId.HasValue, x => x.CurrencyId == currencyId)
                .OrderByIf<SaleProductPrice, IQueryable<SaleProductPrice>>(!sorting.IsNullOrWhiteSpace(), sorting)
                .PageBy(skipCount, maxResultCount)
                .ToListAsync(cancellationToken);

            return entities;
        }
    }
}
